//
//  MarkedSummaryListViewController.m
//  FleaFinder
//
//  Created by Hieu Le on 4/10/13.
//  Copyright (c) 2013 Kiwiweb. All rights reserved.
//

#import "MarkedSummaryListViewController.h"
#import "XmlParserMarkedListInCategory.h"
#import "MarkedSummaryTableViewCell.h"
#import "Marked.h"
#import "MarkedInfo.h"
#import "XmlParserCategoryList.h"
//#import "Common.h"

@interface MarkedSummaryListViewController ()

@end

@implementation MarkedSummaryListViewController

//@synthesize selectedMarketType;
@synthesize categoryList;
@synthesize isNotTopMarkderMode;
@synthesize marketSummaryList;
@synthesize marketSummaryListTableView;
//@synthesize isViewAll;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
  
    font = [UIFont fontWithName:@"Georgia" size:13.0];
    fontBold = [UIFont fontWithName:@"Georgia-Bold" size:13.0];
    font12 = [UIFont fontWithName:@"Georgia" size:12.0];
    commonColor = [UIColor colorWithRed:0.188 green:0.188 blue:0.219 alpha:1.0];
    darkPurpleColor = [UIColor colorWithRed:0.372 green:0.258 blue:0.509 alpha:1.0];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated
{
    if(!appDelegate){
        appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    }
    
    NSDate* now = [NSDate dateWithTimeIntervalSinceNow:0];
    if(now.timeIntervalSince1970 - appDelegate.lastTimeLoadData.timeIntervalSince1970 > appDelegate.common.timeIntervalToReloadMarketList)
    {
        // now check to load new data
        [appDelegate startReadMoreMarketListFromWebsite: self];
    }
    
    if(!isNotTopMarkderMode)
    {
        //[self loadXmlData:nil isViewAll:NO];
        self.navigationItem.title = @"Top Markeder";
        marketSummaryList = appDelegate.businessMarketList;
    }
    
    //start a thread to load markettype list and category list from website.
    
    
    //if(appDelegate.isLoadingMarketList){
        /*CGRect b = self.view.bounds;
        indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleGray];
        //indicator.backgroundColor = [UIColor grayColor];
        indicator.alpha = 1.0;
        //indicator.frame = CGRectMake((b.size.width - 20) / 2, (b.size.height - 20) / 2, 20, 20);
        //center the indicator in the view
        //indicator.frame = CGRectMake((b.size.width - 20) / 2, (b.size.height - 20) / 2, 20, 20);
        indicator.center = CGPointMake(b.size.width / 2, b.size.height / 2);
        [self.view addSubview: indicator];
        //[indicator release];
        [indicator startAnimating];*/
        
        while(!appDelegate.isHasSomeMarketsLoaded){
            sleep(1);
        }
        
        /*[indicator stopAnimating];
        [indicator removeFromSuperview];
        indicator = nil;*/
    //}
    
    /*NSSortDescriptor *sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"datefrom_num" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    
    marketSummaryList = [marketSummaryList sortedArrayUsingDescriptors:sortDescriptors];
    */
    if([marketSummaryList count] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hovsa!" message:@"Vi fandt desværre ikke markeder.\nPrøv igen senere, tak :)!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alert show];
        
        //return;
    }
    
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    [marketSummaryListTableView reloadData];
    
    /*if(!categoryList){
        XmlParserCategoryList *xmlParser = [[XmlParserCategoryList alloc] init];
        [xmlParser parseXML: linkToCategoryList];
        categoryList = [xmlParser getParsedObjects];
    }*/
}

-(void) loadXmlData: (NSString*) fromUrl isViewAll:(BOOL) viewAll
{
    if(!appDelegate){
        appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    }
    
    if(viewAll){
        marketSummaryList = appDelegate.marketList;
    } else {
        NSMutableArray* newDataList = [NSMutableArray arrayWithCapacity:50];
        NSMutableArray* data = [appDelegate.dataOrganized objectForKey:appDelegate.currentSelectedMarketType.name];
        Marked* m = nil;
        for(int i = 0; i < [data count]; ++i){
            m = (Marked*) [data objectAtIndex:i];
            
            if(appDelegate.currentSelectedCategory.categoryId == -1){
                [newDataList addObject:m];
            } else {
                for(int j = 0; j < [m.categories count]; ++j){
                    if(((Category*)[m.categories objectAtIndex:j]).categoryId == appDelegate.currentSelectedCategory.categoryId){
                        [newDataList addObject:m];
                        break;
                    }
                }
            }
        }
        marketSummaryList = newDataList;
    }
    
    if(viewAll){
        [self.navigationItem setTitle: @"VIS ALLE"];
    }
}

-(void) loadXmlData: (NSString*) sourceUrl forMarketType:(MarketType*) marketType andCategory:(Category*) category
{
    [self.navigationItem setTitle: category.title];
    [self loadXmlData:nil isViewAll:NO];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [marketSummaryList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"MarkedSummaryTableViewCell";
    MarkedSummaryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell)
    {
        cell = [[MarkedSummaryTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    cell.lblMarkedName.font = fontBold;
    [cell.lblMarkedName setTextColor:darkPurpleColor];
    
    cell.lblMarkedType.font = font12;
    [cell.lblMarkedType setTextColor:commonColor];
    
     cell.lblAddress.font = font;
    [cell.lblAddress setTextColor:commonColor];
    
     cell.lblDate.font = font12;
    [cell.lblDate setTextColor:commonColor];
    
    cell.lblTime.font = font12;
    [cell.lblTime setTextColor:commonColor];
    
    Marked* m = [marketSummaryList objectAtIndex:indexPath.row];
    cell.lblMarkedName.text = m.markedname;
    
    cell.lblAddress.text = [NSString stringWithFormat:@"%@, %@",m.road,m.city];
    cell.lblTime.text = [NSString stringWithFormat:@"Tid: %@ - %@", m.startat, m.endat];
    cell.lblMarkedType.text = m.type;
    // Configure the cell...
    
   cell.lblDate.text = [NSString stringWithFormat:@"d.%@ - %@", m.datefrom, m.dateto];
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // NSString* linkMarkedInfo;

    if(!appDelegate.markedInfoViewController){
        if(!appDelegate.storyBoard)
            appDelegate.storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
        
        appDelegate.markedInfoViewController = [appDelegate.storyBoard instantiateViewControllerWithIdentifier:@"SBMarkedInfo"];
    }
    
    [appDelegate.markedInfoViewController loadXmlData:appDelegate.common.linkMarkedInfo forMarket:((Marked*)[marketSummaryList objectAtIndex:indexPath.row]).marketId];
    
    [self.navigationController pushViewController:appDelegate.markedInfoViewController animated:YES];
}

-(void) startUpdateNewMarkets
{
    //NSLog(@"SELECTOR PERFORMED");
    [self.marketSummaryListTableView reloadData];
}

@end
